/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bff.gaia.mix.runtime.io;

import com.bff.gaia.annotation.Internal;
import com.bff.gaia.api.common.typeutils.TypeSerializer;
import com.bff.gaia.metrics.Gauge;
import com.bff.gaia.runtime.event.AbstractEvent;
import com.bff.gaia.runtime.io.network.api.writer.RecordWriter;
import com.bff.gaia.runtime.plugable.SerializationDelegate;
import com.bff.gaia.mix.api.operators.Output;
import com.bff.gaia.mix.api.watermark.Watermark;
import com.bff.gaia.mix.runtime.metrics.WatermarkGauge;
import com.bff.gaia.mix.runtime.streamrecord.LatencyMarker;
import com.bff.gaia.mix.runtime.streamrecord.MixStreamElement;
import com.bff.gaia.mix.runtime.streamrecord.MixStreamElementSerializer;
import com.bff.gaia.mix.runtime.streamrecord.MixStreamRecord;
import com.bff.gaia.mix.runtime.streamstatus.MixStreamStatus;
import com.bff.gaia.mix.runtime.streamstatus.MixStreamStatusProvider;
import com.bff.gaia.mix.runtime.tasks.OperatorChain;
import com.bff.gaia.util.OutputTag;

import java.io.IOException;

import static com.bff.gaia.util.Preconditions.checkNotNull;

/**
 * Implementation of {@link Output} that sends data using a {@link RecordWriter}.
 */
@Internal
public class RecordWriterOutput<OUT> implements OperatorChain.WatermarkGaugeExposingOutput<MixStreamRecord<OUT>> {

	private RecordWriter<SerializationDelegate<MixStreamElement>> recordWriter;

	private SerializationDelegate<MixStreamElement> serializationDelegate;

	private final MixStreamStatusProvider streamStatusProvider;

	private final OutputTag outputTag;

	private final WatermarkGauge watermarkGauge = new WatermarkGauge();

	@SuppressWarnings("unchecked")
	public RecordWriterOutput(
			RecordWriter<SerializationDelegate<MixStreamRecord<OUT>>> recordWriter,
			TypeSerializer<OUT> outSerializer,
			OutputTag outputTag,
			MixStreamStatusProvider streamStatusProvider) {

		checkNotNull(recordWriter);
		this.outputTag = outputTag;
		// generic hack: cast the writer to generic Object type so we can use it
		// with multiplexed records and watermarks
		this.recordWriter = (RecordWriter<SerializationDelegate<MixStreamElement>>)
				(RecordWriter<?>) recordWriter;

		TypeSerializer<MixStreamElement> outRecordSerializer =
				new MixStreamElementSerializer<>(outSerializer);

		if (outSerializer != null) {
			serializationDelegate = new SerializationDelegate<MixStreamElement>(outRecordSerializer);
		}

		this.streamStatusProvider = checkNotNull(streamStatusProvider);
	}

	@Override
	public void collect(MixStreamRecord<OUT> record) {
		if (this.outputTag != null) {
			// we are only responsible for emitting to the main input
			return;
		}

		pushToRecordWriter(record);
	}

	@Override
	public <X> void collect(OutputTag<X> outputTag, MixStreamRecord<X> record) {
		if (this.outputTag == null || !this.outputTag.equals(outputTag)) {
			// we are only responsible for emitting to the side-output specified by our
			// OutputTag.
			return;
		}

		pushToRecordWriter(record);
	}

	private <X> void pushToRecordWriter(MixStreamRecord<X> record) {
		serializationDelegate.setInstance(record);

		try {
			recordWriter.emit(serializationDelegate);
		}
		catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public void emitWatermark(Watermark mark) {
		watermarkGauge.setCurrentWatermark(mark.getTimestamp());
		serializationDelegate.setInstance(mark);

		if (streamStatusProvider.getMixStreamStatus().isActive()) {
			try {
				recordWriter.broadcastEmit(serializationDelegate);
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage(), e);
			}
		}
	}

	public void emitMixStreamStatus(MixStreamStatus streamStatus) {
		serializationDelegate.setInstance(streamStatus);

		try {
			recordWriter.broadcastEmit(serializationDelegate);
		}
		catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public void emitLatencyMarker(LatencyMarker latencyMarker) {
		serializationDelegate.setInstance(latencyMarker);

		try {
			recordWriter.randomEmit(serializationDelegate);
		}
		catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public void broadcastEvent(AbstractEvent event) throws IOException {
		recordWriter.broadcastEvent(event);
	}

	public void flush() throws IOException {
		recordWriter.flushAll();
	}

	@Override
	public void close() {
		recordWriter.close();
	}

	@Override
	public Gauge<Long> getWatermarkGauge() {
		return watermarkGauge;
	}
}